package com.hx.jvm.classloader.loader;

import java.io.*;

/**
 * @author jxlgcmh
 * @date 2020-08-02 14:08
 * @description 自定义一个类加载器: MyClassLoader
 */
public class MyClassLoader extends ClassLoader {

    // 类所在的路径
    private String path;

    // 构造方法
    public MyClassLoader(String path) {
        this.path = path;
    }

    // 重写findClass方法
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 定义clazz对象
        Class clazz = null;
        // 获取字节码对象数组
        byte[] bytes = getBytes();
        if (bytes != null) {
            clazz = defineClass(name, bytes, 0, bytes.length);
        }
        return clazz;
    }

    /**
     * 读取字节码文件 获取字节码数组
     *
     * @return
     */
    private byte[] getBytes() {
        File classFile = new File(path);
        if (classFile.exists()) {
            FileInputStream in = null;
            ByteArrayOutputStream out = null;
            try {
                in = new FileInputStream(classFile);
                out = new ByteArrayOutputStream();

                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = in.read(buff)) != -1) {
                    out.write(buff, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return out.toByteArray();
        }
        return null;
    }
}
